package cn.mrlong.base.utils

import android.content.Context
import android.graphics.Color
import android.view.Gravity
import android.widget.TextView
import android.widget.Toast

/**
 * 作者：BINGO
 * 时间：2021/03/29 13:38
 */
class ToastUtil {
    companion object {
        private var oldMessage: String = ""
        private var toast: Toast? = null;
        private var firstTime: Long = 0
        private var secondTime: Long = 0
        fun show(
            context: Context,
            message: String,
            duration: Int = Toast.LENGTH_SHORT,
            gravity: Int = Gravity.CENTER
        ) {
            try {
                if (null == toast) {
                    toast = Toast.makeText(context.applicationContext, message, duration)
                    toast?.setGravity(gravity, 0, 0)
                    toast?.duration = duration
                    try {
                        val textView = toast?.view as? TextView
                        textView?.setBackgroundColor(Color.GRAY)
                        textView?.textSize = 15F
                        textView?.setPadding(25,0,25,0)
                    } catch (e: Exception) {
                    }
                    toast?.show()
                    firstTime = System.currentTimeMillis()
                } else {
                    secondTime = System.currentTimeMillis()
                    if (message == oldMessage) {
                        if ((secondTime - firstTime) > duration) {
                            toast?.show()
                        }
                    } else {
                        oldMessage = message
                        toast?.setText(message)
                        toast?.show()
                    }
                    firstTime = secondTime
                }
            }catch (e:Exception){

            }
        }
    }
}